package com.cdut.hezhisu.dribbble.util;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class DownloadTask extends Thread {
    private String downloadUrl;// 下载链接地址
    private int threadNum;// 开启的线程数
    private String filePath;// 保存文件路径地址
    private int blockSize;// 每一个线程的下载量
    private static final String TAG = "DownloadTask";
    private static final int DOWNLOAD_SUCCESS = 0x11;
    private static final int DOWNLOAD_FAIL = 0x12;
    private DownLoadCallBack mCallBack;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case DOWNLOAD_FAIL:
                    if(mCallBack != null){
                        mCallBack.onFail();
                    }
                    break;
                case DOWNLOAD_SUCCESS:
                    if(mCallBack != null){
                        mCallBack.onSuccess(filePath);
                    }
                    break;
            }
        }
    };
    public DownloadTask(String downloadUrl, int threadNum, String fileptah) {
        this.downloadUrl = downloadUrl;
        this.threadNum = threadNum;
        this.filePath = fileptah;
    }

    public void setDownLoadCallBack(DownLoadCallBack callBack){
        this.mCallBack = callBack;
    }

    @Override
    public void run() {

        FileDownloadThread[] threads = new FileDownloadThread[threadNum];
        try {
            URL url = new URL(downloadUrl);
            Log.d(TAG, "download file http path:" + downloadUrl);
            URLConnection conn = url.openConnection();
            // 读取下载文件总大小
            int fileSize = conn.getContentLength();
            if (fileSize <= 0) {
                System.out.println("读取文件失败");
                return;
            }


            // 计算每条线程下载的数据长度
            blockSize = (fileSize % threadNum) == 0 ? fileSize / threadNum
                    : fileSize / threadNum + 1;

            Log.d(TAG, "fileSize:" + fileSize + "  blockSize:");

            File file = new File(filePath);
            for (int i = 0; i < threads.length; i++) {
                // 启动线程，分别下载每个线程需要下载的部分
                threads[i] = new FileDownloadThread(url, file, blockSize,
                        (i + 1));
                threads[i].setName("Thread:" + i);
                threads[i].start();
            }

            boolean isfinished = false;
            int downloadedAllSize = 0;
            while (!isfinished) {
                isfinished = true;
                // 当前所有线程下载总量
                downloadedAllSize = 0;
                for (int i = 0; i < threads.length; i++) {
                    downloadedAllSize += threads[i].getDownloadLength();
                    if (!threads[i].isCompleted()) {
                        isfinished = false;
                    }
                }

            }
            mHandler.sendEmptyMessage(DOWNLOAD_SUCCESS);

        } catch (MalformedURLException e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(DOWNLOAD_FAIL);
        } catch (IOException e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(DOWNLOAD_FAIL);
        }

    }

    public interface DownLoadCallBack{
        void onSuccess(String path);
        void onFail();
    }
}
